/**
 * AreaController.java
 * Created at 2017-07-06
 * Created by Jackie liu
 * Copyright (C) 2014, All rights reserved.
 */
package com.huabo.controller.base;

import com.huabo.base.BaseController;
import com.huabo.enumeration.YesNoEnum;
import com.huabo.model.Area;
import com.huabo.service.inter.AreaService;
import com.huabo.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>ClassName: AreaController</p>
 * <p>Description: 区域管理Controller</p>
 * <p>Author: Jackie liu</p>
 * <p>Date: 2017-07-06</p>
 */
/**
 * Created by Jackie Liu on 2017/3/18.
 */
@Controller
public class AreaController extends BaseController {

	@Autowired
	private AreaService areaService;

	/**
	 * 添加区域管理
	 *
	 * @param record
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/web/area/save", method = RequestMethod.POST)
	@ResponseBody
	public Response save(Area record, HttpServletRequest request, HttpServletResponse response) {
		Validator validator = new Validator();
		validator.required(request, "name", "区域名称不能为空");
		validator.required(request, "category", "区域 类型不能为空");
		validator.required(request, "code", "区域编码不能为空");
		validator.required(request, "orderBy", "排序序号不能为空");
		if (validator.isError()) {
			return ResponseUtils.warn(validator.getMessage());
		}
		
		boolean duplicateCode = areaService.isDuplicateCode(record.getId(), record.getCode());
		if(duplicateCode){
			return ResponseUtils.warn("区域编码已存在");
		}
		
		boolean duplicateName = areaService.isDuplicateName(record.getId(), record.getName(),record.getParentId());
		if(duplicateName){
			return ResponseUtils.warn("该区域名称已存在");
		}
		record.setId(KeyUtils.getDistributedId());
		record.setState(YesNoEnum.YES_ACCPET.getValue());
		areaService.insert(record);
		return ResponseUtils.success("添加区域成功");
	}

	/**
	 * 修改区域管理
	 *
	 * @param record
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/web/area/modify", method = RequestMethod.POST)
	@ResponseBody
	public Response modify(Area record, HttpServletRequest request, HttpServletResponse response) {
		Validator validator = new Validator();
		validator.required(request, "id", "参数错误");
		validator.required(request, "name", "区域名称不能为空");
		validator.required(request, "category", "区域 类型不能为空");
		validator.required(request, "code", "区域编码不能为空");
		validator.required(request, "orderBy", "排序序号不能为空");
		if (validator.isError()) {
			return ResponseUtils.warn(validator.getMessage());
		}
		
		boolean duplicateCode = areaService.isDuplicateCode(record.getId(), record.getCode());
		if(duplicateCode){
			return ResponseUtils.warn("该区域编码已存在");
		}
		
		boolean duplicateName = areaService.isDuplicateName(record.getId(), record.getName(),record.getParentId());
		if(duplicateName){
			return ResponseUtils.warn("该区域名称已存在");
		}
		areaService.modify(record);
		return ResponseUtils.success("区域信息修改成功");
	}

	/**
	 * 查询区域管理
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/web/area/query", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Response query(HttpServletRequest request, HttpServletResponse response) {
		long id = ServletRequestUtils.getLongParameter(request, "id", -1);
		if (id <= -1) {
			return ResponseUtils.warn("请选中区域信息");
		}
		Area record = areaService.load(id);
		return ResponseUtils.success(record);
	}

	/**
	 * 分页查询区域管理
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/web/area/list", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Response tree(HttpServletRequest request, HttpServletResponse response) {
		String searchInput = ServletRequestUtils.getStringParameter(request, "searchInput", null);
        String parentId = ServletRequestUtils.getStringParameter(request, "parentId", null);

        Map<String, Object> params = new HashMap<String, Object>();
        initParams(params, request);
        params.put("searchInput", searchInput);
        params.put("idPath", parentId);

        Page<Area> page = areaService.queryPage(params);
        return ResponseUtils.success(page);
	}

    /**
     * 拖拽组织机构信息改变从属节点
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/area/drag", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response drag(HttpServletRequest request, HttpServletResponse response) {
        long id = ServletRequestUtils.getLongParameter(request, "id", -1);
        long targetId = ServletRequestUtils.getLongParameter(request, "targetId", -1);
        if (id <= 0 || targetId <= 0) {
            return ResponseUtils.warn("拖拽参数错误");
        }

        areaService.modifyWithDrag(id, targetId);
        return ResponseUtils.success("拖拽成功");
    }

	/**
	 * 批量删除区域信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/web/area/delete", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Response batchRemove(HttpServletRequest request) {
		String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
		if (ids == null) {
			return ResponseUtils.warn("请选择区域信息");
		}
		areaService.batchRemove(WebUtils.toLongArray(ids.split(",")));
		return ResponseUtils.success("删除成功");
	}

	/**
	 * 禁用区域信息,级联其子区域
	 * 
	 * @return
	 */
	@RequestMapping(value = "/web/area/stop", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Response stop(HttpServletRequest request) {
		String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
		if (ids == null) {
			return ResponseUtils.warn("请选择停用的区域");
		}
		List<Long> arrayList = new ArrayList<>();
		String[] idArray = ids.split(",");
		Map<String, Object> params = new HashMap<String, Object>();
		for (int i = 0; i < idArray.length; i++) {
			params.put("idPath", idArray[i]);
			List<Area> list = areaService.query(params);
			for (Area area : list) {
				arrayList.add(area.getId());
			}
		}
		ApiUtils.removeDuplicate(arrayList);
		areaService.modifyState(YesNoEnum.NO_CANCEL.getValue(), arrayList.toArray(new Long[0]));
		return ResponseUtils.success("停用成功");
	}

	/**
	 * 启用区域信息,级联其父区域
	 * 
	 * @return
	 */
	@RequestMapping(value = "/web/area/accpet", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Response accpet(HttpServletRequest request) {
		String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
		if (StringUtils.isEmpty(ids)) {
			return ResponseUtils.warn("请选择启用的区域");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("ids", Arrays.asList(ids.split(",")));
		List<Area> list = areaService.query(params);
		List<Long> parentIdList = new ArrayList<>();
		for (Area area : list) {
			String[] array = area.getIdPath().split("/");
			parentIdList.addAll(Arrays.asList(WebUtils.toLongArray(array)));
		}
		ApiUtils.removeDuplicate(parentIdList);
		areaService.modifyState(YesNoEnum.YES_ACCPET.getValue(), parentIdList.toArray(new Long[0]));
		return ResponseUtils.success("启用成功");
	}

	/**
	 * 区域树列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/web/area/tree", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Response tree(HttpServletRequest request) {
		Map<String, Object> hashMap = new HashMap<>();
		List<Area> list = areaService.query(hashMap);
		List<Tree> treeList = new ArrayList<>();
		for (Area area : list) {
			Tree tree = new Tree(area.getId(), area.getParentId(), area.getName(), area);
			treeList.add(tree);
		}
		return ResponseUtils.success(treeList);
	}
}
